package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;

/**
 * @author wfyn
 * @date 2023/10/4
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Autowired
   AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        // 获取上传文件的原始文件名
        String originalFilename = file.getOriginalFilename();

        // 获取文件扩展名
        String extension = null;
        if (originalFilename != null) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        // 生成随机的文件名，包括扩展名
        String objectName = UUID.randomUUID() + extension;

        try {
            // 调用aliOssUtil的upload方法上传文件，并获取上传后的文件路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            // 返回成功的结果，包含文件路径
            return Result.success(filePath,"文件上传成功");
        } catch (IOException e) {
            // 如果发生IO异常，记录错误日志
            log.error(MessageConstant.UPLOAD_FAILED+e);
        }

        // 如果发生异常，返回上传失败的结果
        return Result.error(MessageConstant.UPLOAD_FAILED);

    }




}
